use anyhow::Result;
use std::process::{Command, Stdio};
use std::thread;
use std::time::{Duration, Instant};
use std::fs;
use std::path::Path;

mod ftp_client_test;
use ftp_client_test::FtpTestClient;

/// 综合测试套件
pub struct ComprehensiveTestSuite {
    server_process: Option<std::process::Child>,
    test_data_dir: String,
}

impl ComprehensiveTestSuite {
    pub fn new() -> Self {
        Self {
            server_process: None,
            test_data_dir: "test_data".to_string(),
        }
    }
    
    /// 启动FTP服务器
    pub fn start_server(&mut self) -> Result<()> {
        println!("🚀 启动FTP服务器...");
        
        // 构建服务器
        let build_result = Command::new("cargo")
            .args(&["build", "-p", "ftp-server"])
            .output()?;
        
        if !build_result.status.success() {
            let error = String::from_utf8_lossy(&build_result.stderr);
            return Err(anyhow::anyhow!("构建失败: {}", error));
        }
        
        // 启动服务器进程
        let server_process = Command::new("cargo")
            .args(&["run", "-p", "ftp-server", "--", "--port", "2121"])
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()?;
        
        self.server_process = Some(server_process);
        
        // 等待服务器启动
        println!("⏳ 等待服务器启动...");
        thread::sleep(Duration::from_secs(3));
        
        println!("✅ FTP服务器已启动 (端口: 2121)");
        Ok(())
    }
    
    /// 停止FTP服务器
    pub fn stop_server(&mut self) -> Result<()> {
        if let Some(mut process) = self.server_process.take() {
            println!("🛑 停止FTP服务器...");
            process.kill()?;
            process.wait()?;
            println!("✅ FTP服务器已停止");
        }
        Ok(())
    }
    
    /// 准备测试数据
    pub fn setup_test_data(&self) -> Result<()> {
        println!("📁 准备测试数据...");
        
        // 创建测试目录
        fs::create_dir_all(&self.test_data_dir)?;
        
        // 创建测试文件
        let test_files = vec![
            ("small_file.txt", "Hello, FTP!"),
            ("medium_file.txt", &"A".repeat(1024 * 10)), // 10KB
            ("large_file.txt", &"B".repeat(1024 * 100)), // 100KB
        ];
        
        for (filename, content) in test_files {
            let path = Path::new(&self.test_data_dir).join(filename);
            fs::write(&path, content)?;
            println!("✅ 创建测试文件: {}", filename);
        }
        
        Ok(())
    }
    
    /// 清理测试数据
    pub fn cleanup_test_data(&self) -> Result<()> {
        println!("🧹 清理测试数据...");
        if Path::new(&self.test_data_dir).exists() {
            fs::remove_dir_all(&self.test_data_dir)?;
        }
        Ok(())
    }
    
    /// 测试基本连接
    pub fn test_basic_connection(&self) -> Result<()> {
        println!("\n=== 测试基本连接 ===");
        
        let mut client = FtpTestClient::connect("localhost", 2121)?;
        let welcome = client.read_response()?;
        println!("✅ 连接成功: {}", welcome);
        
        client.send_command("QUIT")?;
        client.expect_response(221)?;
        
        Ok(())
    }
    
    /// 测试认证系统
    pub fn test_authentication_system(&self) -> Result<()> {
        println!("\n=== 测试认证系统 ===");
        
        let mut client = FtpTestClient::connect("localhost", 2121)?;
        client.read_response()?;
        
        // 测试无效用户
        println!("测试无效用户...");
        client.send_command("USER invaliduser")?;
        client.expect_response(331)?;
        
        client.send_command("PASS wrongpass")?;
        match client.expect_response(530) {
            Ok(_) => println!("✅ 无效认证正确被拒绝"),
            Err(_) => println!("❌ 无效认证未被正确拒绝"),
        }
        
        // 测试有效用户
        println!("测试有效用户...");
        client.send_command("USER testuser")?;
        client.expect_response(331)?;
        
        client.send_command("PASS testpass")?;
        match client.expect_response(230) {
            Ok(_) => println!("✅ 有效认证成功"),
            Err(_) => println!("❌ 有效认证失败"),
        }
        
        client.send_command("QUIT")?;
        client.expect_response(221)?;
        
        Ok(())
    }
    
    /// 测试FTP命令
    pub fn test_ftp_commands(&self) -> Result<()> {
        println!("\n=== 测试FTP命令 ===");
        
        let mut client = FtpTestClient::connect("localhost", 2121)?;
        client.read_response()?;
        
        // 登录
        client.login("testuser", "testpass")?;
        
        // 测试系统命令
        client.test_system_info()?;
        
        // 测试传输模式
        client.test_transfer_modes()?;
        
        // 测试被动模式
        client.test_pasv()?;
        
        // 测试主动模式
        client.test_port()?;
        
        // 测试目录操作
        client.test_directory_operations()?;
        
        // 测试文件操作
        client.test_file_operations()?;
        
        client.send_command("QUIT")?;
        client.expect_response(221)?;
        
        Ok(())
    }
    
    /// 测试文件传输
    pub fn test_file_transfer(&self) -> Result<()> {
        println!("\n=== 测试文件传输 ===");
        
        let mut client = FtpTestClient::connect("localhost", 2121)?;
        client.read_response()?;
        client.login("testuser", "testpass")?;
        
        // 测试文件上传
        println!("测试文件上传...");
        client.send_command("PASV")?;
        let pasv_response = client.expect_response(227)?;
        println!("PASV响应: {}", pasv_response);
        
        client.send_command("STOR test_upload.txt")?;
        match client.expect_response(150) {
            Ok(_) => println!("✅ 文件上传开始"),
            Err(_) => println!("❌ 文件上传失败"),
        }
        
        // 测试文件下载
        println!("测试文件下载...");
        client.send_command("PASV")?;
        client.expect_response(227)?;
        
        client.send_command("RETR test_upload.txt")?;
        match client.expect_response(150) {
            Ok(_) => println!("✅ 文件下载开始"),
            Err(_) => println!("❌ 文件下载失败"),
        }
        
        client.send_command("QUIT")?;
        client.expect_response(221)?;
        
        Ok(())
    }
    
    /// 测试并发连接
    pub fn test_concurrent_connections(&self) -> Result<()> {
        println!("\n=== 测试并发连接 ===");
        
        let mut handles = vec![];
        
        // 创建多个并发连接
        for i in 0..5 {
            let handle = thread::spawn(move || -> Result<()> {
                let mut client = FtpTestClient::connect("localhost", 2121)?;
                client.read_response()?;
                
                println!("连接 {} 成功", i);
                
                // 执行一些基本操作
                client.send_command("SYST")?;
                client.expect_response(215)?;
                
                client.send_command("QUIT")?;
                client.expect_response(221)?;
                
                Ok(())
            });
            
            handles.push(handle);
        }
        
        // 等待所有连接完成
        for (i, handle) in handles.into_iter().enumerate() {
            match handle.join() {
                Ok(Ok(_)) => println!("✅ 并发连接 {} 成功", i),
                Ok(Err(e)) => println!("❌ 并发连接 {} 失败: {}", i, e),
                Err(_) => println!("❌ 并发连接 {} 线程错误", i),
            }
        }
        
        Ok(())
    }
    
    /// 测试性能
    pub fn test_performance(&self) -> Result<()> {
        println!("\n=== 测试性能 ===");
        
        // 测试连接时间
        let start = Instant::now();
        let mut client = FtpTestClient::connect("localhost", 2121)?;
        let connect_time = start.elapsed();
        println!("连接时间: {:?}", connect_time);
        
        client.read_response()?;
        client.login("testuser", "testpass")?;
        
        // 测试命令响应时间
        let commands = vec!["SYST", "PWD", "TYPE I", "NOOP"];
        
        for cmd in commands {
            let start = Instant::now();
            client.send_command(cmd)?;
            client.read_response()?;
            let response_time = start.elapsed();
            println!("命令 {} 响应时间: {:?}", cmd, response_time);
        }
        
        client.send_command("QUIT")?;
        client.expect_response(221)?;
        
        Ok(())
    }
    
    /// 测试错误场景
    pub fn test_error_scenarios(&self) -> Result<()> {
        println!("\n=== 测试错误场景 ===");
        
        let mut client = FtpTestClient::connect("localhost", 2121)?;
        client.read_response()?;
        
        // 测试无效命令
        println!("测试无效命令...");
        client.send_command("INVALID")?;
        match client.expect_response(500) {
            Ok(_) => println!("✅ 无效命令正确被拒绝"),
            Err(_) => println!("❌ 无效命令未被正确拒绝"),
        }
        
        // 测试未认证的命令
        println!("测试未认证命令...");
        client.send_command("PWD")?;
        match client.expect_response(530) {
            Ok(_) => println!("✅ 未认证命令正确被拒绝"),
            Err(_) => println!("❌ 未认证命令未被正确拒绝"),
        }
        
        // 测试不存在的文件
        client.login("testuser", "testpass")?;
        println!("测试不存在的文件...");
        client.send_command("SIZE nonexistent.txt")?;
        match client.expect_response(550) {
            Ok(_) => println!("✅ 不存在文件正确被拒绝"),
            Err(_) => println!("❌ 不存在文件未被正确拒绝"),
        }
        
        client.send_command("QUIT")?;
        client.expect_response(221)?;
        
        Ok(())
    }
    
    /// 测试断点续传
    pub fn test_resume_transfer(&self) -> Result<()> {
        println!("\n=== 测试断点续传 ===");
        
        let mut client = FtpTestClient::connect("localhost", 2121)?;
        client.read_response()?;
        client.login("testuser", "testpass")?;
        
        // 测试REST命令
        client.send_command("REST 100")?;
        match client.expect_response(350) {
            Ok(_) => println!("✅ 断点续传支持"),
            Err(_) => println!("❌ 断点续传不支持"),
        }
        
        client.send_command("QUIT")?;
        client.expect_response(221)?;
        
        Ok(())
    }
    
    /// 运行完整测试套件
    pub fn run_comprehensive_test(&mut self) -> Result<()> {
        println!("🧪 开始综合测试套件");
        
        // 准备测试环境
        self.setup_test_data()?;
        
        // 启动服务器
        self.start_server()?;
        
        // 运行各种测试
        self.test_basic_connection()?;
        self.test_authentication_system()?;
        self.test_ftp_commands()?;
        self.test_file_transfer()?;
        self.test_concurrent_connections()?;
        self.test_performance()?;
        self.test_error_scenarios()?;
        self.test_resume_transfer()?;
        
        // 清理
        self.stop_server()?;
        self.cleanup_test_data()?;
        
        println!("🎉 综合测试完成！");
        Ok(())
    }
}

fn main() -> Result<()> {
    let mut test_suite = ComprehensiveTestSuite::new();
    test_suite.run_comprehensive_test()
}
